<?php
/* ========== ########## ========== ########## ========== ########## ========== */
/*                                                                              */
/*   WHMCS v4.1.2 NULLED R4 by FLIPMODE  [ BAD SYNTAX ]                         */
/*                                                                              */
/*                             INTERNAL BAD SYNTAX NULLED VERSION: 2.5.9.6 R4   */
/*                                                                              */
/*   ALL files have been analysed, cleaned and nulled of:                       */
/*     - Call Backs  (100%)                                                     */
/*     - Link Backs (95%)                                                       */
/*     - Licensing  (100%)                                                      */
/*     - Remote Links + URL's                                                   */
/*                                                                              */
/*   WHMCS v4.1.2 RELEASED: 4th November 2009                                   */
/*    -> FIRST v4.1.2 NULL R1: 19th November 2009                               */
/*    -> UPDATED v4.1.2 NULL R4: 27th November 2009                             */
/*                                                                              */
/*   TESTING + VERIFICATION::                                                   */
/*     Files Cleaned, Nulled, Checked, Verified By:                             */
/*      -> FLIPMODE!                                                            */
/*     Decoded By:                                                              */
/*      -> FLIPMODE! + Unknown Decoder                                          */
/*     Tested By:                                                               */
/*      -> FLIPMODE!, LeetWolf, and 12 Anonymous Users...                       */
/*     WHMCS 4.1.2 Supplied By:                                                 */
/*      -> WHM CompleteShit Coder @ WHMCS.com                                   */
/*                                                                              */
/*                                                                              */
/*   IMPORTANT NOTE::                                                           */
/*   PLEASE NOTE THIS IS FOR TRIAL PURPOSES ONLY!                               */
/*                          LIKE IT? THEN BUY IT!                               */
/*                                                                              */
/* ========== ########## ========== ########## ========== ########## ========== */

define ('CLIENTAREA', true);
require 'dbconnect.php';
require 'includes/functions.php';
require 'includes/clientareafunctions.php';
require 'includes/orderfunctions.php';
require 'includes/domainfunctions.php';
require 'includes/whoisfunctions.php';
require 'includes/configoptionsfunctions.php';
require 'includes/customfieldfunctions.php';
require 'includes/clientfunctions.php';
require 'includes/invoicefunctions.php';
require 'includes/processinvoices.php';
require 'includes/gatewayfunctions.php';
require 'includes/fraudfunctions.php';
require 'includes/modulefunctions.php';
$orderform = 'true';
$errormessage = '';
if ($carttpl)
{
	$_SESSION['CartTemplate'] = $carttpl;
}

if ($_SESSION['CartTemplate'])
{
	$CONFIG['OrderFormTemplate'] = $_SESSION['CartTemplate'];
}

$pagetitle = $_LANG['carttitle'];
$breadcrumbnav = '<a href="cart.php">' . $_LANG['carttitle'] . '</a>';
$pageicon = 'images/order_big.gif';
initialiseclientarea ($pagetitle, $pageicon, $breadcrumbnav);
$currency = getcurrency ($_SESSION['uid'], $_SESSION['currency']);
$smartyvalues['currency'] = $currency;
$smartyvalues['ipaddress'] = $remote_ip;
if ($step == 'fraudcheck')
{
	$a = 'fraudcheck';
}

if ($promocode)
{
	setpromocode ($promocode);
}

if ($a == 'empty')
{
	unset ($_SESSION[cart]);
	header ('Location: cart.php?a=view');
	exit ();
}

if ($a == 'startover')
{
	unset ($_SESSION[cart]);
	header ('Location: cart.php');
	exit ();
}

if ($a == 'remove')
{
	if ($r == 'p')
	{
		unset ($_SESSION['cart']['products'][$i]);
		$_SESSION['cart']['products'] = array_values ($_SESSION['cart']['products']);
	}
	else
	{
		if ($r == 'a')
		{
			unset ($_SESSION['cart']['addons'][$i]);
			$_SESSION['cart']['addons'] = array_values ($_SESSION['cart']['addons']);
		}
		else
		{
			if ($r == 'd')
			{
				unset ($_SESSION['cart']['domains'][$i]);
				$_SESSION['cart']['domains'] = array_values ($_SESSION['cart']['domains']);
			}
		}
	}

	header ('Location: cart.php?a=view');
	exit ();
}

if (((!$a OR ($a == 'add' AND $pid)) AND ((($sld AND $tld) AND !is_array ($sld)) OR is_array ($domains))))
{
	if (is_array ($domains))
	{
		$tempdomain = $domains[0];
		$tempdomain = explode ('.', $tempdomain, 2);
		$sld = $tempdomain[0];
		$tld = '.' . $tempdomain[1];
	}

	$_SESSION['cartdomain']['sld'] = $sld;
	$_SESSION['cartdomain']['tld'] = $tld;
}

if (!$a)
{
	if ($CONFIG['AllowRegister'])
	{
		$smartyvalues['registerdomainenabled'] = true;
	}

	if ($CONFIG['AllowTransfer'])
	{
		$smartyvalues['transferdomainenabled'] = true;
	}

	if ($gid == 'domains')
	{
		header ('Location: cart.php?a=add&domain=register');
		exit ();
	}
	else
	{
		if ($gid == 'addons')
		{
			$templatefile = 'addons';
			$productgroups = getproductgroups ();
			$smarty->assign ('productgroups', $productgroups);
			$where = array ();
			$where['userid'] = $_SESSION['uid'];
			$where['domainstatus'] = 'Active';
			if ($pid)
			{
				$where['tblhosting.id'] = $pid;
			}

			$productids = array ();
			$result = select_query ('tblhosting', 'tblhosting.id,domain,packageid,name', $where, '', '', '', 'tblproducts ON tblproducts.id=tblhosting.packageid');
			while ($data = mysql_fetch_array ($result))
			{
				$productstoids[$data['packageid']][] = array ('id' => $data['id'], 'product' => $data['name'], 'domain' => $data['domain']);
				if (!in_array ($data['packageid'], $productids))
				{
					$productids[] = $data['packageid'];
					continue;
				}
			}

			$addonids = array ();
			$result = select_query ('tbladdons', 'id,packages', '', 'name', 'ASC');
			while ($data = mysql_fetch_array ($result))
			{
				$id = $data['id'];
				$packages = $data['packages'];
				$packages = explode (',', $packages);
				foreach ($productids as $productid)
				{
					if (in_array ($productid, $productids))
					{
						if (!in_array ($id, $addonids))
						{
							$addonids[] = $id;
							continue;
						}

						continue;
					}
				}
			}

			$addons = array ();
			if (count ($addonids))
			{
				$result = select_query ('tbladdons', '', 'id IN (' . implode ($addonids, ',') . ')', 'name', 'ASC');
				while ($data = mysql_fetch_array ($result))
				{
					$addonid = $data['id'];
					$packages = $data['packages'];
					$packages = explode (',', $packages);
					$name = $data['name'];
					$description = $data['description'];
					$billingcycle = $data['billingcycle'];
					$free = $data['free'];
					$result2 = select_query ('tblpricing', '', array ('type' => 'addon', 'currency' => $currency['id'], 'relid' => $addonid));
					$data = mysql_fetch_array ($result2);
					$setupfee = $data['msetupfee'];
					$recurring = $data['monthly'];
					if ($setupfee == '0.00')
					{
						$setupfee = '';
					}
					else
					{
						$setupfee = formatcurrency ($setupfee);
					}

					$newproductbillingcycle = strtolower ($billingcycle);
					$newproductbillingcycle = str_replace (' ', '', $newproductbillingcycle);
					$newproductbillingcycle = str_replace ('-', '', $newproductbillingcycle);
					$billingcycle = $_LANG['orderpaymentterm' . $newproductbillingcycle];
					$packageids = array ();
					foreach ($packages as $packageid)
					{
						$thisaddonspackages = '';
						$thisaddonspackages = $productstoids[$packageid];
						if ($thisaddonspackages)
						{
							$packageids = array_merge ($packageids, $thisaddonspackages);
							continue;
						}
					}

					if (count ($packageids))
					{
						$addons[] = array ('id' => $addonid, 'name' => $name, 'description' => $description, 'free' => $free, 'setupfee' => $setupfee, 'recurringamount' => formatcurrency ($recurring), 'billingcycle' => $billingcycle, 'productids' => $packageids);
						continue;
					}
				}
			}

			$smarty->assign ('addons', $addons);
			if (!count ($addons))
			{
				$smarty->assign ('noaddons', true);
			}
		}
		else
		{
			$templatefile = 'products';
			$productgroups = getproductgroups ();
			$products = getproducts ($gid);
			if (!$gid)
			{
				$result = select_query ('tblproductgroups', '', array ('hidden' => ''), 'order', 'ASC');
				$data = mysql_fetch_array ($result);
				$gid = $data['id'];
			}

			$smarty->assign ('gid', $gid);
			$smarty->assign ('productgroups', $productgroups);
			$smarty->assign ('products', $products);
		}
	}
}

if ($a == 'add')
{
	if ($pid)
	{
		$templatefile = 'configureproductdomain';
		$smartyvalues['pid'] = $pid;
		$result = select_query ('tblproducts', '', array ('id' => $pid));
		$data = mysql_fetch_array ($result);
		$type = $data['type'];
		if (!$type)
		{
			header ('Location: cart.php');
			exit ();
		}

		$subdomain = $data['subdomain'];
		$freedomain = $data['freedomain'];
		$freedomaintlds = $data['freedomaintlds'];
		$showdomainoptions = $data['showdomainoptions'];
		$stockcontrol = $data['stockcontrol'];
		$qty = $data['qty'];
		if (($stockcontrol AND $qty <= 0))
		{
			$templatefile = 'fraudcheck';
			$smartyvalues['errortitle'] = $_LANG['outofstock'];
			$smartyvalues['error'] = $_LANG['outofstockdescription'];
			outputclientarea ($templatefile);
			exit ();
		}

		$passedvariables = array ();
		if ($billingcycle)
		{
			$passedvariables['billingcycle'] = $billingcycle;
		}

		if ($configoption)
		{
			foreach ($configoption as $k => $v)
			{
				$passedvariables['configoption[' . (int)$k . ']'] = (int)$v;
			}
		}

		if ($customfield)
		{
			foreach ($customfield as $k => $v)
			{
				$passedvariables['customfield[' . (int)$k . ']'] = $v;
			}
		}

		if ($addons)
		{
			foreach ($addons as $k => $v)
			{
				$passedvariables['addons[' . (int)$k . ']'] = $v;
			}
		}

		$smartyvalues['passedvariables'] = $passedvariables;
		if (($showdomainoptions AND !$domains))
		{
			$productinfo = getproductinfo ($pid);
			$smartyvalues['productinfo'] = $productinfo;
			$cartproducts = $_SESSION['cart']['products'];
			$cartdomains = $_SESSION['cart']['domains'];
			if ($cartdomains)
			{
				foreach ($cartdomains as $cartdomain)
				{
					$domainname = $cartdomain['domain'];
					if ($cartproducts)
					{
						foreach ($cartproducts as $cartproduct)
						{
							if ($cartproduct['domain'] == $domainname)
							{
								$domainname = '';
								continue;
							}
						}
					}

					if ($domainname)
					{
						$incartdomains[] = $domainname;
						continue;
					}
				}
			}

			if ($incartdomains)
			{
				if (!$domainoption)
				{
					$domainoption = 'incart';
				}
			}

			if ($CONFIG['AllowRegister'])
			{
				if (!$domainoption)
				{
					$domainoption = 'register';
				}
			}

			if ($CONFIG['AllowTransfer'])
			{
				if (!$domainoption)
				{
					$domainoption = 'transfer';
				}
			}

			if ($CONFIG['AllowOwnDomain'])
			{
				if (!$domainoption)
				{
					$domainoption = 'owndomain';
				}
			}

			if ($subdomain)
			{
				if (!$domainoption)
				{
					$domainoption = 'subdomain';
				}
			}

			$registertlds = gettldlist ();
			$transfertlds = gettldlist ('transfer');
			$smartyvalues['listtld'] = $registertlds;
			$smartyvalues['registertlds'] = $registertlds;
			$smartyvalues['transfertlds'] = $transfertlds;
			$smartyvalues['showdomainoptions'] = true;
			$smartyvalues['domainoption'] = $domainoption;
			$smartyvalues['registerdomainenabled'] = $CONFIG['AllowRegister'];
			$smartyvalues['transferdomainenabled'] = $CONFIG['AllowTransfer'];
			$smartyvalues['owndomainenabled'] = $CONFIG['AllowOwnDomain'];
			$smartyvalues['subdomain'] = $subdomain;
			$smartyvalues['incartdomains'] = $incartdomains;
			if (($freedomain AND $freedomaintlds))
			{
				$smartyvalues['freedomaintlds'] = $freedomaintlds;
			}

			if (is_array ($tld))
			{
				if ($domainoption == 'register')
				{
					$tld = $tld[0];
					$sld = $sld[0];
				}
				else
				{
					if ($domainoption == 'transfer')
					{
						$tld = $tld[1];
						$sld = $sld[1];
					}
					else
					{
						if ($domainoption == 'owndomain')
						{
							$tld = $tld[2];
							$sld = $sld[2];
						}
						else
						{
							if ($domainoption == 'subdomain')
							{
								$tld = $subdomain;
								$sld = $sld[3];
							}
							else
							{
								if ($domainoption == 'incart')
								{
									$incartdomain = explode ('.', $incartdomain, 2);
									$tld = $incartdomain[1];
									$sld = $incartdomain[0];
								}
							}
						}
					}
				}
			}

			if (((((!$sld AND !$tld) AND isset ($_SESSION['cartdomain'])) AND $domainoption == 'register') AND in_array ($_SESSION['cartdomain']['tld'], $registertlds)))
			{
				$sld = $_SESSION['cartdomain']['sld'];
				$tld = $_SESSION['cartdomain']['tld'];
			}

			$sld = trim (strtolower ($sld));
			$tld = trim (strtolower ($tld));
			$sld = ereg_replace ('[^a-z0-9.-]', '', $sld);
			$tld = ereg_replace ('[^a-z0-9.-]', '', $tld);
			if (substr ($sld, 0 - 1) == '.')
			{
				$sld = substr ($sld, 0, 0 - 1);
			}

			if (($sld AND $tld))
			{
				if ((($domainoption == 'register' AND !in_array ($tld, $registertlds)) OR ($domainoption == 'transfer' AND !in_array ($tld, $transfertlds))))
				{
					$sld = '';
					$tld = '';
				}
			}

			$smartyvalues['sld'] = $sld;
			$smartyvalues['tld'] = $tld;
			if (($tld AND substr ($tld, 0, 1) != '.'))
			{
				$tld = '.' . $tld;
			}

			if ($sld)
			{
				if ($domainoption == 'subdomain')
				{
					if (!checkdomainisvalid ($sld, '.com'))
					{
						$errormessage .= $_LANG['ordererrordomaininvalid'];
					}

					$result = select_query ('tblhosting', 'COUNT(*)', '' . 'domain=\'' . $sld . $tld . '\' AND (domainstatus!=\'Terminated\' AND domainstatus!=\'Cancelled\' AND domainstatus!=\'Fraud\')');
					$data = mysql_fetch_array ($result);
					$subchecks = $data[0];
					if ($subchecks)
					{
						$errormessage = '<li>' . $_LANG['ordererrorsubdomaintaken'];
					}
				}
				else
				{
					if (!checkdomainisvalid ($sld, $tld))
					{
						$errormessage .= $_LANG['ordererrordomaininvalid'];
					}

					if ((($domainoption == 'register' OR $domainoption == 'transfer') AND $CONFIG['AllowDomainsTwice']))
					{
						$result = select_query ('tbldomains', 'COUNT(*)', '' . 'domain=\'' . $sld . $tld . '\' AND (status!=\'Expired\' AND status!=\'Cancelled\' AND status!=\'Fraud\')');
						$data = mysql_fetch_array ($result);
						$domaincheck = $data[0];
						if ($domaincheck)
						{
							$errormessage = '<li>' . $_LANG['ordererrordomainalreadyexists'];
						}
					}
					else
					{
						if (($domainoption == 'owndomain' AND $CONFIG['AllowDomainsTwice']))
						{
							$result = select_query ('tblhosting', 'COUNT(*)', '' . 'domain=\'' . $sld . $tld . '\' AND (domainstatus!=\'Terminated\' AND domainstatus!=\'Cancelled\' AND domainstatus!=\'Fraud\')');
							$data = mysql_fetch_array ($result);
							$domaincheck = $data[0];
							if ($domaincheck)
							{
								$errormessage = '<li>' . $_LANG['ordererrordomainalreadyexists'];
							}
						}
					}
				}

				$smartyvalues['errormessage'] = $errormessage;
			}

			if (!$errormessage)
			{
				if ((($domainoption == 'register' OR $domainoption == 'transfer') AND ($sld AND $tld)))
				{
					if ($domainoption == 'register')
					{
						$searchvar = 'available';
					}
					else
					{
						$searchvar = 'unavailable';
					}

					$smartyvalues['searchvar'] = $searchvar;
					$result = lookupdomain ($sld, $tld);
					$regoptions = array ();
					if ($result['result'] == $searchvar)
					{
						$regoptions = gettldpricelist ($tld, true);
					}

					$availabilityresults[] = array ('domain' => $sld . $tld, 'status' => $result['result'], 'regoptions' => $regoptions);
					$tldslist = $CONFIG['BulkCheckTLDs'];
					if (($tldslist AND $domainoption == 'register'))
					{
						$tldslist = explode (',', $tldslist);
						foreach ($tldslist as $lookuptld)
						{
							if ($lookuptld != $tld)
							{
								$result = lookupdomain ($sld, $lookuptld);
								$regoptions = array ();
								if ($result['result'] == $searchvar)
								{
									$regoptions = gettldpricelist ($lookuptld, true);
								}

								$availabilityresults[] = array ('domain' => $sld . $lookuptld, 'status' => $result['result'], 'regoptions' => $regoptions);
								continue;
							}
						}
					}

					$smartyvalues['availabilityresults'] = $availabilityresults;
					$smartyvalues['domains'] = $domains;
				}

				if (((($domainoption == 'owndomain' OR $domainoption == 'subdomain') OR $domainoption == 'incart') AND ($sld AND $tld)))
				{
					$smartyvalues['showdomainoptions'] = false;
					$domains = array ($sld . $tld);
					$productconfig = true;
				}
			}
		}
		else
		{
			$productconfig = true;
		}

		if ($productconfig)
		{
			$_SESSION['cart']['products'][] = array ('pid' => $pid, 'domain' => $domains[0], 'billingcycle' => $billingcycle, 'configoptions' => $configoption, 'customfields' => $customfield, 'addons' => $addons, 'noconfig' => true);
			if (($domainoption == 'register' OR $domainoption == 'transfer'))
			{
				foreach ($domains as $domainname)
				{
					$_SESSION['cart']['domains'][] = array ('type' => $domainoption, 'domain' => $domainname, 'regperiod' => $domainsregperiod[$domainname]);
				}
			}

			$_SESSION['cart']['newproduct'] = true;
			header ('Location: cart.php?a=confproduct&i=' . (count ($_SESSION['cart']['products']) - 1));
			exit ();
		}
	}
	else
	{
		if ($aid)
		{
			if (!$_POST['productid'])
			{
				exit ('Addon Parent Product ID Not Present');
			}

			$_SESSION['cart']['addons'][] = array ('id' => $_POST['aid'], 'productid' => $_POST['productid']);
			header ('Location: cart.php?a=view');
			exit ();
		}
		else
		{
			if ($domain)
			{
				if ($CONFIG['AllowRegister'])
				{
					$smartyvalues['registerdomainenabled'] = true;
				}

				if ($CONFIG['AllowTransfer'])
				{
					$smartyvalues['transferdomainenabled'] = true;
				}

				if ($domains)
				{
					$addtocartok = true;
					if ($addtocartok)
					{
						foreach ($domains as $domainname)
						{
							$_SESSION['cart']['domains'][] = array ('type' => $domain, 'domain' => $domainname, 'regperiod' => $domainsregperiod[$domainname], 'eppcode' => $eppcode);
						}

						header ('Location: cart.php?a=confdomains');
						exit ();
					}
				}

				$templatefile = 'adddomain';
				$productgroups = getproductgroups ();
				$smarty->assign ('productgroups', $productgroups);
				$smartyvalues['domain'] = $domain;
				if ($domain == 'register')
				{
					$tldslist = gettldlist ();
				}
				else
				{
					$tldslist = gettldlist ('transfer');
				}

				if ((((!$sld AND !$tld) AND isset ($_SESSION['cartdomain'])) AND in_array ($_SESSION['cartdomain']['tld'], $tldslist)))
				{
					$sld = $_SESSION['cartdomain']['sld'];
					$tld = $_SESSION['cartdomain']['tld'];
				}

				$sld = strtolower ($sld);
				$tld = strtolower ($tld);
				$sld = ereg_replace ('[^a-z0-9.-]', '', $sld);
				$tld = ereg_replace ('[^a-z0-9.-]', '', $tld);
				if (($sld AND $tld))
				{
					if (!in_array ($tld, $tldslist))
					{
						$sld = '';
						$tld = '';
					}
				}

				if (!$domains)
				{
					$domains[] = $sld . $tld;
				}

				$smartyvalues['domains'] = $domains;
				$smartyvalues['tlds'] = $tldslist;
				$smartyvalues['sld'] = $sld;
				$smartyvalues['tld'] = $tld;
				if (($sld AND $tld))
				{
					if (!checkdomainisvalid ($sld, $tld))
					{
						$errormessage .= $_LANG['ordererrordomaininvalid'];
					}

					if ($CONFIG['AllowDomainsTwice'])
					{
						$result = select_query ('tbldomains', 'COUNT(*)', '' . 'domain=\'' . $sld . $tld . '\' AND (status!=\'Expired\' AND status!=\'Cancelled\')');
						$data = mysql_fetch_array ($result);
						$domaincheck = $data[0];
						if ($domaincheck)
						{
							$errormessage .= '<li>' . $_LANG['ordererrordomainalreadyexists'];
						}
					}

					$smartyvalues['errormessage'] = $errormessage;
				}

				if ((($sld AND $tld) AND !$errormessage))
				{
					if ($domain == 'register')
					{
						$searchvar = 'available';
					}
					else
					{
						$searchvar = 'unavailable';
					}

					$smarty->assign ('searchvar', $searchvar);
					$result = lookupdomain ($sld, $tld);
					$regoptions = array ();
					if ($result['result'] == $searchvar)
					{
						$regoptions = gettldpricelist ($tld, true);
					}

					$availabilityresults[] = array ('domain' => $sld . $tld, 'status' => $result['result'], 'regoptions' => $regoptions);
					$tldslist = $CONFIG['BulkCheckTLDs'];
					if (($tldslist AND $domain == 'register'))
					{
						$tldslist = explode (',', $tldslist);
						foreach ($tldslist as $lookuptld)
						{
							if ($lookuptld != $tld)
							{
								$result = lookupdomain ($sld, $lookuptld);
								$regoptions = array ();
								if ($result['result'] == $searchvar)
								{
									$regoptions = gettldpricelist ($lookuptld, true);
								}

								$availabilityresults[] = array ('domain' => $sld . $lookuptld, 'status' => $result['result'], 'regoptions' => $regoptions);
								continue;
							}
						}
					}

					$smarty->assign ('availabilityresults', $availabilityresults);
				}
			}
			else
			{
				header ('Location: cart.php');
				exit ();
			}
		}
	}
}

if ($a == 'confproduct')
{
	$templatefile = 'configureproduct';
	if (!is_array ($_SESSION['cart']['products'][$i]))
	{
		header ('Location: cart.php');
		exit ();
	}

	$newproduct = $_SESSION['cart']['newproduct'];
	unset ($_SESSION['cart'][newproduct]);
	if ($configure)
	{
		$errormessage = '';
		$result = select_query ('tblproducts', 'type', array ('id' => $_SESSION['cart']['products'][$i]['pid']));
		$data = mysql_fetch_array ($result);
		$producttype = $data['type'];
		if ($producttype == 'server')
		{
			if (!$hostname)
			{
				$errormessage .= '<li>' . $_LANG['ordererrorservernohostname'];
			}

			if ((!$ns1prefix OR !$ns2prefix))
			{
				$errormessage .= '<li>' . $_LANG['ordererrorservernonameservers'];
			}

			if (!$rootpw)
			{
				$errormessage .= '<li>' . $_LANG['ordererrorservernorootpw'];
			}

			$serverarray = array ('hostname' => $hostname, 'ns1prefix' => $ns1prefix, 'ns2prefix' => $ns2prefix, 'rootpw' => $rootpw);
		}

		if ($customfield)
		{
			foreach ($customfield as $key => $value)
			{
				$customfieldsarray[sanitize ($key)] = sanitize ($value);
			}
		}

		if ($configoption)
		{
			foreach ($configoption as $opid => $opid2)
			{
				$result = select_query ('tblproductconfigoptions', '', array ('id' => $opid));
				$data = mysql_fetch_array ($result);
				$optionname = $data['optionname'];
				$optiontype = $data['optiontype'];
				$qtyminimum = $data['qtyminimum'];
				$qtymaximum = $data['qtymaximum'];
				if ($optiontype == 4)
				{
					$opid2 = (int)$opid2;
					if ($opid2 < 0)
					{
						$opid2 = 0;
					}

					if ((($qtyminimum OR $qtymaximum) AND ($opid2 < $qtyminimum OR $qtymaximum < $opid2)))
					{
						$errormessage .= '<li>' . sprintf ($_LANG['configoptionqtyminmax'], $optionname, $qtyminimum, $qtymaximum);
						$opid2 = 0;
					}
				}

				$configoptionsarray[sanitize ($opid)] = sanitize ($opid2);
			}
		}

		if ($addons)
		{
			foreach ($addons as $addonid => $discard)
			{
				$addonsarray[] = $addonid;
			}
		}

		$_SESSION['cart']['products'][$i]['billingcycle'] = $billingcycle;
		$_SESSION['cart']['products'][$i]['server'] = $serverarray;
		$_SESSION['cart']['products'][$i]['configoptions'] = $configoptionsarray;
		$_SESSION['cart']['products'][$i]['customfields'] = $customfieldsarray;
		$_SESSION['cart']['products'][$i]['addons'] = $addonsarray;
		if ($previousbillingcycle != $billingcycle)
		{
			header ('' . 'Location: cart.php?a=confproduct&i=' . $i);
			exit ();
		}

		$errormessage .= checkcustomfields ($customfield);
		if ($errormessage)
		{
			$smartyvalues['errormessage'] = $errormessage;
		}
		else
		{
			unset ($_SESSION['cart']['products'][$i][noconfig]);
			header ('Location: cart.php?a=confdomains');
			exit ();
		}
	}

	$pid = $_SESSION['cart']['products'][$i]['pid'];
	$billingcycle = $_SESSION['cart']['products'][$i]['billingcycle'];
	$server = $_SESSION['cart']['products'][$i]['server'];
	$customfields = $_SESSION['cart']['products'][$i]['customfields'];
	$configoptions = $_SESSION['cart']['products'][$i]['configoptions'];
	$addons = $_SESSION['cart']['products'][$i]['addons'];
	$domain = $_SESSION['cart']['products'][$i]['domain'];
	if (!$billingcycle)
	{
		$result = select_query ('tblproducts', 'paytype', array ('id' => $pid));
		$data = mysql_fetch_array ($result);
		$paytype = $data['paytype'];
		$result = select_query ('tblpricing', '', array ('type' => 'product', 'currency' => $currency['id'], 'relid' => $pid));
		$data = mysql_fetch_array ($result);
		$monthly = $data['monthly'];
		$quarterly = $data['quarterly'];
		$semiannually = $data['semiannually'];
		$annually = $data['annually'];
		$biennially = $data['biennially'];
		if ($paytype == 'free')
		{
			$billingcycle = 'free';
		}
		else
		{
			if ($paytype == 'onetime')
			{
				$billingcycle = 'onetime';
			}
			else
			{
				if ($paytype == 'recurring')
				{
					if (0 <= $monthly)
					{
						$billingcycle = 'monthly';
					}
					else
					{
						if (0 <= $quarterly)
						{
							$billingcycle = 'quarterly';
						}
						else
						{
							if (0 <= $semiannually)
							{
								$billingcycle = 'semiannually';
							}
							else
							{
								if (0 <= $annually)
								{
									$billingcycle = 'annually';
								}
								else
								{
									if (0 <= $biennially)
									{
										$billingcycle = 'biennially';
									}
								}
							}
						}
					}
				}
			}
		}
	}

	$productinfo = getproductinfo ($pid);
	$pricing = getpricinginfo ($pid);
	$configurableoptions = getcartconfigoptions ($pid, $configoptions, $billingcycle);
	$customfields = getcustomfields ('product', $pid, '', '', 'on', $customfields);
	if (!$addons)
	{
		$addons = array ();
	}

	$addonsarray = array ();
	$result = select_query ('tbladdons', '', array ('showorder' => 'on'), 'name', 'ASC');
	while ($data = mysql_fetch_array ($result))
	{
		$addon_id = $data['id'];
		$addon_packages = $data['packages'];
		$addon_name = $data['name'];
		$addon_description = $data['description'];
		$addon_recurring = $data['recurring'];
		$addon_setupfee = $data['setupfee'];
		$addon_billingcycle = $data['billingcycle'];
		$addon_free = $data['free'];
		$result2 = select_query ('tblpricing', '', array ('type' => 'addon', 'currency' => $currency['id'], 'relid' => $addon_id));
		$data = mysql_fetch_array ($result2);
		$addon_setupfee = $data['msetupfee'];
		$addon_recurring = $data['monthly'];
		$addon_packages = explode (',', $addon_packages);
		if (in_array ($pid, $addon_packages))
		{
			$addon_checkbox = ('' . '<input type="checkbox" name="addons[' . $addon_id . ']') . '" id="a' . $addon_id . '"';
			if (in_array ($addon_id, $addons))
			{
				$addon_checkbox .= ' checked';
			}

			$addon_checkbox .= ' />';
			$addon_pricingdetails = '';
			if ($addon_billingcycle == 'Free')
			{
				$addon_pricingdetails .= $_LANG['orderfree'];
			}
			else
			{
				$addon_pricingdetails .= formatcurrency ($addon_recurring) . ' ';
				$addon_billingcycle = str_replace (' ', '', $addon_billingcycle);
				$addon_billingcycle = str_replace ('-', '', $addon_billingcycle);
				$addon_billingcycle = strtolower ($addon_billingcycle);
				$addon_pricingdetails .= $_LANG['orderpaymentterm' . $addon_billingcycle];
				if (0 < $setupfee)
				{
					$addon_pricingdetails .= ' + ' . formatcurrency ($addon_setupfee) . ' ' . $_LANG['ordersetupfee'];
				}
			}

			$addonsarray[] = array ('id' => $addon_id, 'checkbox' => $addon_checkbox, 'name' => $addon_name, 'description' => $addon_description, 'pricing' => $addon_pricingdetails);
			continue;
		}
	}

	$recurringcycles = 0;
	if ($pricing['type'] == 'recurring')
	{
		if (0 <= $pricing['rawpricing']['monthly'])
		{
			++$recurringcycles;
		}

		if (0 <= $pricing['rawpricing']['quarterly'])
		{
			++$recurringcycles;
		}

		if (0 <= $pricing['rawpricing']['semiannually'])
		{
			++$recurringcycles;
		}

		if (0 <= $pricing['rawpricing']['annually'])
		{
			++$recurringcycles;
		}

		if (0 <= $pricing['rawpricing']['biennially'])
		{
			++$recurringcycles;
		}
	}

	if ((((($newproduct AND ($pricing['type'] != 'recurring' OR $recurringcycles <= 1)) AND !count ($configurableoptions)) AND !count ($customfields)) AND !count ($addonsarray)))
	{
		unset ($_SESSION['cart']['products'][$i][noconfig]);
		header ('Location: cart.php?a=view');
		exit ();
	}

	$serverarray = array ('hostname' => $server['hostname'], 'ns1prefix' => $server['ns1prefix'], 'ns2prefix' => $server['ns2prefix'], 'rootpw' => $server['rootpw']);
	$smartyvalues['editconfig'] = true;
	$smartyvalues['i'] = $i;
	$smartyvalues['productinfo'] = $productinfo;
	$smartyvalues['pricing'] = $pricing;
	$smartyvalues['billingcycle'] = $billingcycle;
	$smartyvalues['server'] = $serverarray;
	$smartyvalues['configurableoptions'] = $configurableoptions;
	$smartyvalues['addons'] = $addonsarray;
	$smartyvalues['customfields'] = $customfields;
	$smartyvalues['domain'] = $domain;
}

if ($a == 'confdomains')
{
	$templatefile = 'configuredomains';
	$skipstep = true;
	$_SESSION['cartdomain'] = '';
	include 'includes/additionaldomainfields.php';
	if ($update)
	{
		$domains = $_SESSION['cart']['domains'];
		foreach ($domains as $key => $domainname)
		{
			$_SESSION['cart']['domains'][$key]['dnsmanagement'] = $_POST['dnsmanagement'][$key];
			$_SESSION['cart']['domains'][$key]['emailforwarding'] = $_POST['emailforwarding'][$key];
			$_SESSION['cart']['domains'][$key]['idprotection'] = $_POST['idprotection'][$key];
			$_SESSION['cart']['domains'][$key]['eppcode'] = $_POST['epp'][$key];
			$domainparts = explode ('.', $domainname['domain'], 2);
			if ($domainname['type'] == 'register')
			{
				$tempdomainfields = $additionaldomainfields['.' . $domainparts[1]];
				if ($tempdomainfields)
				{
					foreach ($tempdomainfields as $fieldnum => $values)
					{
						if (($values['Required'] AND !$domainfield[$key][$fieldnum]))
						{
							$errormessage .= '<li>' . $values['Name'] . ' ' . $_LANG['clientareaerrorisrequired'] . ' (' . $domainname['domain'] . ')';
						}

						$_SESSION['cart']['domains'][$key]['fields'][$fieldnum] = $domainfield[$key][$fieldnum];
					}

					continue;
				}

				continue;
			}
			else
			{
				$result = select_query ('tbldomainpricing', '', array ('extension' => '.' . $domainparts[1]));
				$data = mysql_fetch_array ($result);
				if ($data['eppcode'])
				{
					if (!$_POST['epp'][$key])
					{
						$errormessage .= '<li>' . $_LANG['domaineppcoderequired'] . ' ' . $domainname['domain'];
						continue;
					}

					continue;
				}

				continue;
			}
		}

		$_SESSION['cart']['ns1'] = $domainns1;
		$_SESSION['cart']['ns2'] = $domainns2;
		$_SESSION['cart']['ns3'] = $domainns3;
		$_SESSION['cart']['ns4'] = $domainns4;
		if ($errormessage)
		{
			$smartyvalues['errormessage'] = $errormessage;
		}
		else
		{
			header ('Location: cart.php?a=view');
			exit ();
		}
	}

	$domains = $_SESSION['cart']['domains'];
	if ($domains)
	{
		foreach ($domains as $key => $domainname)
		{
			$regperiod = $domainname['regperiod'];
			$domainparts = explode ('.', $domainname['domain'], 2);
			$sld = $domainparts[0];
			$tld = $domainparts[1];
			$result = select_query ('tbldomainpricing', '', array ('extension' => '' . '.' . $tld));
			$data = mysql_fetch_array ($result);
			$domainconfigsshowing = false;
			if ($data['dnsmanagement'])
			{
				$domainconfigsshowing = true;
			}

			if ($data['emailforwarding'])
			{
				$domainconfigsshowing = true;
			}

			if ($data['idprotection'])
			{
				$domainconfigsshowing = true;
			}

			$result = select_query ('tblpricing', '', array ('type' => 'domainaddons', 'currency' => $currency['id'], 'relid' => 0));
			$data2 = mysql_fetch_array ($result);
			$domaindnsmanagementprice = $data2['msetupfee'] * $regperiod;
			$domainemailforwardingprice = $data2['qsetupfee'] * $regperiod;
			$domainidprotectionprice = $data2['ssetupfee'] * $regperiod;
			if ($domaindnsmanagementprice == '0.00')
			{
				$domaindnsmanagementprice = $_LANG['orderfree'];
			}
			else
			{
				$domaindnsmanagementprice = formatcurrency ($domaindnsmanagementprice);
			}

			if ($domainemailforwardingprice == '0.00')
			{
				$domainemailforwardingprice = $_LANG['orderfree'];
			}
			else
			{
				$domainemailforwardingprice = formatcurrency ($domainemailforwardingprice);
			}

			if ($domainidprotectionprice == '0.00')
			{
				$domainidprotectionprice = $_LANG['orderfree'];
			}
			else
			{
				$domainidprotectionprice = formatcurrency ($domainidprotectionprice);
			}

			if (($data['eppcode'] AND $domainname['type'] == 'transfer'))
			{
				$eppenabled = true;
				$domainconfigsshowing = true;
			}
			else
			{
				$eppenabled = false;
			}

			unset ($domainfields);
			unset ($tempdomainfields);
			if ($domainname['type'] == 'register')
			{
				$tempdomainfields = $additionaldomainfields['.' . $tld];
				if ($tempdomainfields)
				{
					$domainconfigsshowing = true;
					foreach ($tempdomainfields as $fieldkey => $value)
					{
						$storedvalue = $domainname['fields'][$fieldkey];
						if ($storedvalue)
						{
							$value['Default'] = $storedvalue;
						}

						if ($value['Type'] == 'text')
						{
							$input = '<input type="text" size="' . $value['Size'] . (((('' . '" name="domainfield[' . $key . ']') . '[') . $fieldkey . ']') . '" value="') . $value['Default'] . '" />';
							if ($value['Required'])
							{
								$input .= ' *';
							}
						}
						else
						{
							if ($value['Type'] == 'dropdown')
							{
								$input = ((('' . '<select name="domainfield[' . $key . ']') . '[') . $fieldkey . ']') . '">';
								$fieldoptions = explode (',', $value['Options']);
								foreach ($fieldoptions as $optionvalue)
								{
									$input .= ('' . '<option value="' . $optionvalue . '"');
									if ($value['Default'] == $optionvalue)
									{
										$input .= ' selected';
									}

									$input .= '' . '>' . $optionvalue . '</option>';
								}

								$input .= '</select>';
							}
							else
							{
								if ($value['Type'] == 'tickbox')
								{
									$input = (((('' . '<input type="checkbox" name="domainfield[' . $key . ']') . '[') . $fieldkey . ']') . '"');
									if ($value['Default'] == 'on')
									{
										$input .= ' checked';
									}

									$input .= '>';
								}
								else
								{
									if ($value['Type'] == 'radio')
									{
										$fieldoptions = explode (',', $value['Options']);
										$input = '';
										foreach ($fieldoptions as $optionvalue)
										{
											$input .= (((('' . '<input type="radio" name="domainfield[' . $key . ']') . '[') . $fieldkey . ']') . '" value="' . $optionvalue . '"');
											if ($value['Default'] == $optionvalue)
											{
												$input .= ' checked';
											}

											$input .= '' . ' /> ' . $optionvalue . '<br>';
										}
									}
								}
							}
						}

						$domainfields[$value['Name']] = $input;
					}
				}
			}

			$products = $_SESSION['cart']['products'];
			$hashosting = false;
			if ($products)
			{
				foreach ($products as $product)
				{
					if ($product['domain'] == $domainname['domain'])
					{
						$hashosting = true;
						continue;
					}
				}
			}

			if (!$hashosting)
			{
				$atleastonenohosting = true;
			}

			if ($atleastonenohosting)
			{
				$skipstep = false;
			}

			$domainsarray[$key] = array ('domain' => $domainname['domain'], 'regperiod' => $domainname['regperiod'], 'dnsmanagement' => $data['dnsmanagement'], 'emailforwarding' => $data['emailforwarding'], 'idprotection' => $data['idprotection'], 'dnsmanagementprice' => $domaindnsmanagementprice, 'emailforwardingprice' => $domainemailforwardingprice, 'idprotectionprice' => $domainidprotectionprice, 'dnsmanagementselected' => $domainname['dnsmanagement'], 'emailforwardingselected' => $domainname['emailforwarding'], 'idprotectionselected' => $domainname['idprotection'], 'eppenabled' => $eppenabled, 'eppvalue' => $domainname['eppcode'], 'fields' => $domainfields, 'configtoshow' => $domainconfigsshowing, 'hosting' => $hashosting);
			if (((((($domainconfigsshowing OR $eppenabled) OR $domainfields) OR $data['dnsmanagement']) OR $data['emailforwarding']) OR $data['idprotection']))
			{
				$skipstep = false;
				continue;
			}
		}
	}

	$smartyvalues['domains'] = $domainsarray;
	$smartyvalues['atleastonenohosting'] = $atleastonenohosting;
	if (((!$skipstep AND !$_SESSION['cart']['ns1']) AND !$_SESSION['cart']['ns2']))
	{
		$_SESSION['cart']['ns1'] = $CONFIG['DefaultNameserver1'];
		$_SESSION['cart']['ns2'] = $CONFIG['DefaultNameserver2'];
		$_SESSION['cart']['ns3'] = $CONFIG['DefaultNameserver3'];
		$_SESSION['cart']['ns4'] = $CONFIG['DefaultNameserver4'];
	}

	$smartyvalues['domainns1'] = $_SESSION['cart']['ns1'];
	$smartyvalues['domainns2'] = $_SESSION['cart']['ns2'];
	$smartyvalues['domainns3'] = $_SESSION['cart']['ns3'];
	$smartyvalues['domainns4'] = $_SESSION['cart']['ns4'];
	if ($skipstep)
	{
		header ('Location: cart.php?a=view');
		exit ();
	}
}

if ($a == 'removepromo')
{
	$_SESSION['cart']['promo'] = '';
	header ('Location: cart.php?a=view');
	exit ();
}

if ($a == 'checkout')
{
	$domainconfigerror = false;
	include 'includes/additionaldomainfields.php';
	$domains = $_SESSION['cart']['domains'];
	if ($domains)
	{
		foreach ($domains as $key => $domainname)
		{
			$domainparts = explode ('.', $domainname['domain'], 2);
			if ($domainname['type'] == 'register')
			{
				$tempdomainfields = $additionaldomainfields['.' . $domainparts[1]];
				$domainfields = $domainname['fields'];
				if ($tempdomainfields)
				{
					foreach ($tempdomainfields as $fieldnum => $values)
					{
						if (($values['Required'] AND !$domainfields[$fieldnum]))
						{
							$domainconfigerror = true;
							continue;
						}
					}

					continue;
				}

				continue;
			}
			else
			{
				$result = select_query ('tbldomainpricing', '', array ('extension' => '.' . $domainparts[1]));
				$data = mysql_fetch_array ($result);
				if (($data['eppcode'] AND !$domainname['eppcode']))
				{
					$domainconfigerror = true;
					continue;
				}

				continue;
			}
		}
	}

	if ($domainconfigerror)
	{
		header ('Location: cart.php?a=confdomains');
		exit ();
	}

	$checkout = true;
	$a = view;
}

if ($a == 'addcontact')
{
	$checkout = true;
	$addcontact = true;
	$a = view;
}

if ($a == 'view')
{
	$templatefile = 'viewcart';
	$readytocompletecheckout = '';
	$securityquestions = getsecurityquestions ('');
	$smartyvalues['securityquestions'] = $securityquestions;
	if ($submit)
	{
		$_SESSION['cart']['paymentmethod'] = $paymentmethod;
		$_SESSION['cart']['notes'] = $notes;
		if (!$_SESSION['uid'])
		{
			$_SESSION['cart']['user'] = array ('firstname' => sanitize ($firstname), 'lastname' => sanitize ($lastname), 'companyname' => sanitize ($companyname), 'email' => sanitize ($email), 'address1' => sanitize ($address1), 'address2' => sanitize ($address2), 'city' => sanitize ($city), 'state' => sanitize ($state), 'postcode' => sanitize ($postcode), 'country' => sanitize ($country), 'phonenumber' => sanitize ($phonenumber));
			$errormessage = checkdetailsarevalid ($firstname, $lastname, $email, $address1, $city, $state, $postcode, $phonenumber, $password, $password2);
			$errormessage .= checkpasswordstrength ($password);
			if (($securityquestions AND !$securityqans))
			{
				$errormessage .= '<li>' . $_LANG['securityanswerrequired'];
			}

			if ($password == '')
			{
				$errormessage .= '<li>' . $_LANG['ordererrorpassword'];
			}

			$errormessage .= checkcustomfields ($customfield);
		}

		if ($contact == 'new')
		{
			header ('Location: cart.php?a=addcontact');
			exit ();
		}

		if ($contact == 'addingnew')
		{
			$errormessage .= checkcontactdetails ($domaincontactfirstname, $domaincontactlastname, $domaincontactemail, $domaincontactaddress1, $domaincontactcity, $domaincontactstate, $domaincontactpostcode, $domaincontactphonenumber);
		}

		if (($CONFIG['EnableTOSAccept'] == 'on' AND $accepttos != 'on'))
		{
			$errormessage .= '<li>' . $_LANG['ordererroraccepttos'];
		}

		if ($_POST['updateonly'])
		{
			$errormessage = '';
		}
		else
		{
			if (!$errormessage)
			{
				$readytocompletecheckout = true;
			}
		}

		if ($readytocompletecheckout)
		{
			if (!$_SESSION['uid'])
			{
				$userid = addclient ($firstname, $lastname, $companyname, $email, $address1, $address2, $city, $state, $postcode, $country, $phonenumber, $password, $securityqid, $securityqans);
				savecustomfields ($_SESSION['uid'], $customfield);
			}

			if ($contact == 'addingnew')
			{
				$contact = addcontact ($_SESSION['uid'], $domaincontactfirstname, $domaincontactlastname, $domaincontactcompanyname, $domaincontactemail, $domaincontactaddress1, $domaincontactaddress2, $domaincontactcity, $domaincontactstate, $domaincontactpostcode, $domaincontactcountry, $domaincontactphonenumber);
			}

			$_SESSION['cart']['contact'] = $contact;
			$carttotals = calccarttotals (true);
			header ('Location: cart.php?a=fraudcheck');
			exit ();
		}

		if (!$paymentmethod)
		{
			$errormessage .= '<li>No payment gateways available so order cannot proceed';
		}
	}

	$smartyvalues['errormessage'] = $errormessage;
	if ($promocode)
	{
		$promoerrormessage = setpromocode ($promocode);
		if ($promoerrormessage)
		{
			$smartyvalues['errormessage'] = '<li>' . $promoerrormessage;
		}
	}

	if ((!$_SESSION['uid'] AND !$_SESSION['cart']['user']['country']))
	{
		$_SESSION['cart']['user']['country'] = $CONFIG['DefaultCountry'];
	}

	$smartyvalues['promotioncode'] = $_SESSION['cart']['promo'];
	$carttotals = calccarttotals ();
	$promotype = $carttotals['promotype'];
	$promovalue = $carttotals['promovalue'];
	$promorecurring = $carttotals['promorecurring'];
	if ($promotype == 'Percentage')
	{
		$promodescription = $promovalue . '%';
	}
	else
	{
		$promodescription = $CONFIG['CurrencySymbol'] . $promovalue;
	}

	$promodescription .= ' ' . $promorecurring . ' ' . $_LANG['orderdiscount'];
	$smartyvalues['promotiondescription'] = $promodescription;
	$smartyvalues['products'] = $carttotals['products'];
	$smartyvalues['addons'] = $carttotals['addons'];
	$smartyvalues['domains'] = $carttotals['domains'];
	$smartyvalues['subtotal'] = $carttotals['subtotal'];
	$smartyvalues['discount'] = $carttotals['discount'];
	$smartyvalues['taxenabled'] = $CONFIG['TaxEnabled'];
	$smartyvalues['taxrate'] = $carttotals['taxrate'];
	$smartyvalues['taxname'] = $carttotals['taxname'];
	$smartyvalues['taxtotal'] = $carttotals['totaltax'];
	$smartyvalues['taxrate2'] = $carttotals['taxrate2'];
	$smartyvalues['taxname2'] = $carttotals['taxname2'];
	$smartyvalues['taxtotal2'] = $carttotals['totaltax2'];
	$smartyvalues['total'] = $carttotals['totalonetime'];
	$smartyvalues['totalrecurringmonthly'] = $carttotals['totalrecurringmonthly'];
	$smartyvalues['totalrecurringquarterly'] = $carttotals['totalrecurringquarterly'];
	$smartyvalues['totalrecurringsemiannually'] = $carttotals['totalrecurringsemiannually'];
	$smartyvalues['totalrecurringannually'] = $carttotals['totalrecurringannually'];
	$smartyvalues['totalrecurringbiennially'] = $carttotals['totalrecurringbiennially'];
	$smartyvalues['proratadate'] = $carttotals['proratadate'];
	$disabledgateways = '';
	if ($_SESSION['cart']['products'])
	{
		foreach ($_SESSION['cart']['products'] as $values)
		{
			$result = select_query ('tblproducts', 'gid', array ('id' => $values['pid']));
			$data = mysql_fetch_array ($result);
			$gid = $data['gid'];
			$result = select_query ('tblproductgroups', 'disabledgateways', array ('id' => $gid));
			$data = mysql_fetch_array ($result);
			$disabledgateways .= $data['disabledgateways'];
		}
	}

	$disabledgateways = explode (',', $disabledgateways);
	$paymentmethod = $_SESSION['cart']['paymentmethod'];
	$gatewayslist = showpaymentgatewayslist ($disabledgateways);
	if (!$paymentmethod)
	{
		$paymentmethod = $gatewayslist[0]['sysname'];
	}

	$smartyvalues['selectedgateway'] = $paymentmethod;
	$smartyvalues['gateways'] = $gatewayslist;
	$cartitems = count ($_SESSION['cart']['products']) + count ($_SESSION['cart']['addons']) + count ($_SESSION['cart']['domains']);
	if (!$cartitems)
	{
		$checkout = false;
	}

	$smartyvalues['cartitems'] = $cartitems;
	$smartyvalues['checkout'] = $checkout;
	$smartyvalues['ipaddress'] = $_SERVER['REMOTE_ADDR'];
	include 'includes/countries.php';
	if ($_SESSION['uid'])
	{
		$clientsdetails = getclientsdetails ();
	}
	else
	{
		$clientsdetails = $_SESSION['cart']['user'];
		$customfields = getcustomfields ('client', '', '', '', 'on', $customfield);
	}

	$smartyvalues['clientsdetails'] = $clientsdetails;
	$smartyvalues['clientcountrydropdown'] = getcountriesdropdown ($country);
	$smartyvalues['customfields'] = $customfields;
	$smartyvalues['shownotesfield'] = $CONFIG['ShowNotesFieldonCheckout'];
	if (!$notes)
	{
		$notes = $_LANG['ordernotesdescription'];
	}

	$smartyvalues['notes'] = $notes;
	$smartyvalues['accepttos'] = $CONFIG['EnableTOSAccept'];
	$smartyvalues['tosurl'] = $CONFIG['TermsOfService'];
	if (count ($_SESSION['cart']['domains']))
	{
		$smartyvalues['domainsinorder'] = true;
	}

	if ($contact == 'addingnew')
	{
		$addcontact = true;
	}

	$result = select_query ('tblcontacts', '', array ('userid' => $_SESSION['uid']), 'firstname` ASC,`lastname', 'ASC');
	while ($data = mysql_fetch_array ($result))
	{
		$domaincontacts[] = array ('id' => $data['id'], 'name' => $data['firstname'] . ' ' . $data['lastname']);
	}

	$smartyvalues['domaincontacts'] = $domaincontacts;
	$smartyvalues['addcontact'] = $addcontact;
	$smartyvalues['domaincontact'] = array ('firstname' => $domaincontactfirstname, 'lastname' => $domaincontactlastname, 'companyname' => $domaincontactcompanyname, 'email' => $domaincontactemail, 'address1' => $domaincontactaddress1, 'address2' => $domaincontactaddress2, 'city' => $domaincontactcity, 'state' => $domaincontactstate, 'postcode' => $domaincontactpostcode, 'country' => $domaincontactcountry, 'phonenumber' => $domaincontactphonenumber);
	$smartyvalues['domaincontactcountrydropdown'] = getcountriesdropdown ($domaincontactcountry, 'domaincontactcountry');
}

if ($a == 'login')
{
	$templatefile = 'login';
	if ($incorrect)
	{
		$smartyvalues['incorrect'] = true;
	}
}

if ($a == 'fraudcheck')
{
	$fraudmodule = getactivefraudmodule ();
	if ($CONFIG['SkipFraudForExisting'])
	{
		$result = select_query ('tblorders', 'COUNT(*)', array ('status' => 'Active', 'userid' => $_SESSION['uid']));
		$data = mysql_fetch_array ($result);
		if ($data[0])
		{
			$fraudmodule = '';
		}
	}

	$result = full_query ('SELECT COUNT(*) FROM tblinvoices INNER JOIN tblorders ON tblorders.invoiceid=tblinvoices.id WHERE tblorders.id=\'' . mysql_real_escape_string ($_SESSION['orderdetails']['OrderID']) . '\' AND tblinvoices.status=\'Paid\'');
	$data = mysql_fetch_array ($result);
	if ($data[0])
	{
		$fraudmodule = '';
	}

	if (!$fraudmodule)
	{
		header ('Location: cart.php?a=complete');
		exit ();
	}

	logactivity ('Order ID ' . $_SESSION['orderdetails']['OrderID'] . ' Fraud Check Initiated');
	update_query ('tblorders', array ('status' => 'Fraud'), array ('id' => $_SESSION['orderdetails']['OrderID']));
	if ($_SESSION['orderdetails']['Products'])
	{
		foreach ($_SESSION['orderdetails']['Products'] as $productid)
		{
			update_query ('tblhosting', array ('domainstatus' => 'Fraud'), array ('id' => $productid));
		}
	}

	if ($_SESSION['orderdetails']['Addons'])
	{
		foreach ($_SESSION['orderdetails']['Addons'] as $addonid)
		{
			update_query ('tblhostingaddons', array ('status' => 'Fraud'), array ('id' => $addonid));
		}
	}

	if ($_SESSION['orderdetails']['Domains'])
	{
		foreach ($_SESSION['orderdetails']['Domains'] as $domainid)
		{
			update_query ('tbldomains', array ('status' => 'Fraud'), array ('id' => $domainid));
		}
	}

	update_query ('tblinvoices', array ('status' => 'Cancelled'), array ('id' => $_SESSION['orderdetails']['InvoiceID']));
	include 'includes/countriescallingcodes.php';
	$clientsdetails = getclientsdetails ($_SESSION['uid']);
	$params = getfraudconfigoptions ($fraudmodule);
	$params['ip'] = $remote_ip;
	$params['forwardedip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
	$params['clientsdetails'] = $clientsdetails;
	$countrycode = $params['clientsdetails']['country'];
	$params['clientsdetails']['countrycode'] = $countrycallingcodes[$countrycode];
	$params['clientsdetails']['phonenumber'] = str_replace ('(', '', $params['clientsdetails']['phonenumber']);
	$params['clientsdetails']['phonenumber'] = str_replace (')', '', $params['clientsdetails']['phonenumber']);
	$params['clientsdetails']['phonenumber'] = str_replace (' ', '', $params['clientsdetails']['phonenumber']);
	$params['clientsdetails']['phonenumber'] = str_replace ('-', '', $params['clientsdetails']['phonenumber']);
	include '' . 'modules/fraud/' . $fraudmodule . '/' . $fraudmodule . '.php';
	$results = dofraudcheck ($params);
	$error = $results['error'];
	$fraudoutput = '';
	if ($results)
	{
		foreach ($results as $key => $value)
		{
			if (((($key != 'userinput' AND $key != 'title') AND $key != 'description') AND $key != 'error'))
			{
				$fraudoutput .= ('' . $key . ' => ' . $value . '
');
				continue;
			}
		}
	}

	update_query ('tblorders', array ('fraudmodule' => $fraudmodule, 'fraudoutput' => $fraudoutput), array ('id' => $_SESSION['orderdetails']['OrderID']));
	if ($results['userinput'])
	{
		logactivity ('Order ID ' . $_SESSION['orderdetails']['OrderID'] . ' Fraud Check Awaiting User Input');
		$templatefile = 'fraudcheck';
		$smarty->assign ('errortitle', $results['title']);
		$smarty->assign ('error', $results['description']);
		outputclientarea ($templatefile);
		exit ();
	}

	if ($error)
	{
		logactivity ('Order ID ' . $_SESSION['orderdetails']['OrderID'] . ' Failed Fraud Check');
		$templatefile = 'fraudcheck';
		$smarty->assign ('errortitle', $error['title']);
		$smarty->assign ('error', $error['description']);
		outputclientarea ($templatefile);
		exit ();
	}
	else
	{
		update_query ('tblorders', array ('status' => 'Pending'), array ('id' => $_SESSION['orderdetails']['OrderID']));
		if ($_SESSION['orderdetails']['Products'])
		{
			foreach ($_SESSION['orderdetails']['Products'] as $productid)
			{
				update_query ('tblhosting', array ('domainstatus' => 'Pending'), array ('id' => $productid));
			}
		}

		if ($_SESSION['orderdetails']['Addons'])
		{
			foreach ($_SESSION['orderdetails']['Addons'] as $addonid)
			{
				update_query ('tblhostingaddons', array ('status' => 'Pending'), array ('id' => $addonid));
			}
		}

		if ($_SESSION['orderdetails']['Domains'])
		{
			foreach ($_SESSION['orderdetails']['Domains'] as $domainid)
			{
				update_query ('tbldomains', array ('status' => 'Pending'), array ('id' => $domainid));
			}
		}

		update_query ('tblinvoices', array ('status' => 'Unpaid'), array ('id' => $_SESSION['orderdetails']['InvoiceID']));
		logactivity ('Order ID ' . $_SESSION['orderdetails']['OrderID'] . ' Passed Fraud Check');
		header ('Location: cart.php?a=complete');
		exit ();
	}
}

if ($a == 'complete')
{
	if (!is_array ($_SESSION['orderdetails']))
	{
		header ('Location: cart.php');
		exit ();
	}

	$result = select_query ('tblhosting', 'tblhosting.id,tblproducts.servertype', array ('tblhosting.orderid' => $_SESSION['orderdetails']['OrderID'], 'tblhosting.domainstatus' => 'Pending', 'tblproducts.autosetup' => 'order'), '', '', '', 'tblproducts ON tblproducts.id=tblhosting.packageid');
	while ($data = mysql_fetch_array ($result))
	{
		$id = $data['id'];
		$servertype = $data['servertype'];
		logactivity ('Running Module Create on Order');
		include_once ROOTDIR . ('' . '/modules/servers/' . $servertype . '/' . $servertype . '.php');
		$result = servercreateaccount ($id);
		if ($result == 'success')
		{
			sendmessage ('defaultnewacc', $id);
			continue;
		}
	}

	if (!$_SESSION['orderdetails']['paymentcomplete'])
	{
		$result = select_query ('tblpaymentgateways', 'value', array ('gateway' => $_SESSION['orderdetails']['PaymentMethod'], 'setting' => 'type'));
		$data = mysql_fetch_array ($result);
		$gatewaytype = $data['value'];
		if ((($_SESSION['orderdetails']['InvoiceID'] AND ($gatewaytype == 'CC' OR $gatewaytype == 'OfflineCC')) AND ($CONFIG['AutoRedirectoInvoice'] == 'on' OR $CONFIG['AutoRedirectoInvoice'] == 'gateway')))
		{
			$gatewaypath = ROOTDIR . '/modules/gateways/' . $_SESSION['orderdetails']['PaymentMethod'] . '.php';
			if (file_exists ($gatewaypath))
			{
				require_once $gatewaypath;
			}

			if (!function_exists ($_SESSION['orderdetails']['PaymentMethod'] . '_link'))
			{
				header ('Location: creditcard.php?invoiceid=' . $_SESSION['orderdetails']['InvoiceID']);
				exit ();
			}
		}

		if (($_SESSION['orderdetails']['InvoiceID'] AND $CONFIG['AutoRedirectoInvoice'] == 'on'))
		{
			header ('Location: viewinvoice.php?id=' . $_SESSION['orderdetails']['InvoiceID']);
			exit ();
		}

		if (($_SESSION['orderdetails']['InvoiceID'] AND $CONFIG['AutoRedirectoInvoice'] == 'gateway'))
		{
			$result = select_query ('tblinvoices', '', array ('userid' => $_SESSION['uid'], 'id' => $_SESSION['orderdetails']['InvoiceID']));
			$data = mysql_fetch_array ($result);
			$id = $data['id'];
			$total = $data['total'];
			$paymentmethod = $data['paymentmethod'];
			$clientsdetails = getclientsdetails ($_SESSION['uid']);
			$params = getgatewayvariables ($paymentmethod, $id, $total);
			$paymentbutton = call_user_func ($paymentmethod . '_link', $params);
			unset ($orderform);
			$templatefile = 'forwardpage';
			$smarty->assign ('message', $_LANG['forwardingtogateway']);
			$smarty->assign ('code', $paymentbutton);
			$smarty->assign ('invoiceid', $id);
			outputclientarea ($templatefile);
			exit ();
		}
	}

	$result = select_query ('tblorders', '', array ('userid' => $_SESSION['uid'], 'id' => $_SESSION['orderdetails']['OrderID']));
	$data = mysql_fetch_array ($result);
	$amount = $data['amount'];
	$paymentmethod = $data['paymentmethod'];
	$templatefile = 'complete';
	$smartyvalues = array ('orderid' => $_SESSION['orderdetails']['OrderID'], 'ordernumber' => $_SESSION['orderdetails']['OrderNumber'], 'invoiceid' => $_SESSION['orderdetails']['InvoiceID'], 'ispaid' => $_SESSION['orderdetails']['paymentcomplete'], 'amount' => $amount, 'paymentmethod' => $paymentmethod, 'clientdetails' => getclientsdetails ($_SESSION['uid']));
}

outputclientarea ($templatefile);
?>